package com.wangyadong.hobby.thread.miscellaneous;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2019/7/213:09
 **/
public class Miscellaneous {

    public static void main(String[] args) throws InterruptedException {
//        ThreadGroup group = new ThreadGroup("youlishu");
//        testThreadGroupInterrupt(group);
//        group.destroy();
//        TimeUnit.SECONDS.sleep(1);
//        group.interrupt();
//        group.destroy();

        testUncaughExceptionWhenRunCatch();
    }


    public static void testUncaughExceptionWhenRunCatch() throws InterruptedException {

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    int i = 1 / 0;
                    System.out.println("end acess" + i);
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + "发生异常还会在UncaughException中捕获吗 ================" + e);
                }
                System.out.println("捕获异常之后还会在执行码？");

            }
        });

        thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            Thread thread = new Thread();
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                thread = t;
                System.out.println(t.getName() + "发送异常-》" + e + " thread status->" + t.getState().name());
            }
        });
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        thread.stop();
    }

    public static void testThreadGroupInterrupt(ThreadGroup group) {
        IntStream.range(0, 10).forEach(i -> {

            Thread thread = new Thread(group, new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(Thread.currentThread().getName() + "begin acess the testThreadGroupInterrupt method");
                        TimeUnit.SECONDS.sleep(3);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        System.out.println(Thread.currentThread().getName() + "end ocuur error when acees the method");
                    }
                    System.out.println(Thread.currentThread().getName() + "end acess the testThreadGroupInterrupt method");
                }
            });
            thread.start();
            thread.stop();
            thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {

                }
            });
        });
    }
}
